<template>
  <div class="app-container">
    医院设置添加
    <el-card class="box-card" style="margin-top: 50px">
      <el-form label-width="120px">
        <el-form-item label="医院名称">
          <el-input v-model="hospset.hosname"/>
        </el-form-item>
        <el-form-item label="医院编号">
          <el-input v-model="hospset.hoscode"/>
        </el-form-item>
        <el-form-item label="api地址">
          <el-input v-model="hospset.apiUrl"/>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="hospset.contactsName"/>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="hospset.contactsPhone"/>
        </el-form-item>
        <el-form-item>
          <!-- :disabled防止重复提交 -->
          <el-button
            :disabled="saveBtnDisabled"
            type="primary"
            @click="saveOrUpdate"
          >保存
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import hospSet from "@/api/hospital/hospset";

export default {
  data() {
    return {
      hospset: {},
      saveBtnDisabled: false, // 保存按钮是否禁用,
    };
  },
  created() {
    /**
     * 进入update页面触发:
     *    0. 仅修改时触发 (if判断,有参数且参数为id)
     *    1. 获取url路径中的id值 (使用vue封装的this.$route.params.id)
     *    2. 调用方法根据id查询
     *    3. 回显
     */
    if (this.$route.params && this.$route.params.id) {
      const id = this.$route.params.id;
      this.fetchDataById(id);
    }
  },
  methods: {
    /**
     * 回显数据思路:
     *  1.根据id查询医院设置记录
     */
    fetchDataById(id) {
      hospSet.getHospSetById(id).then((response) => {
        this.hospset = response.data.hospitalSet;
      });
    },
    /**
     * 添加或修改思路:
     * 1. 首先要防止表单重复提交
     * 2. 所在行没有id就是保存;所在行有id就是修改
     */
    saveOrUpdate() {
      this.saveBtnDisabled = true;
      if (!this.hospset.id) {
        this.saveData();
      } else {
        this.updateData();
      }
    },
    /**
     * 添加思路:
     * 1. 路由跳转
     * 2. 弹出提示信息-保存成功
     * 3. 路由跳转回展示页面
     *
     */
    saveData() {
      hospSet.saveHospSet(this.hospset).then((response) => {
        return this.$message({
          type: "success",
          message: "保存成功!",
        });
      }).then((resposne) => {
        this.$router.push({path: "/hospset/list"});
      }).catch(res => {
          this.saveBtnDisabled = false;
        }
      )
    },
    /**
     * 修改思路:
     *    1. 路由跳转
     *    2. 回显(根据id获取记录)
     *    3. 点击保存后执行修改
     *    4. 路由跳转回展示页面
     */
    updateData() {
      hospSet.updateHospSet(this.hospset).then((response) => {
        return this.$message({
          type: "success",
          message: "修改成功!",
        });
      }).then((resposne) => {
        this.$router.push({path: "/hospset/list"});
      }).catch(res => {
          this.saveBtnDisabled = false;
        }
      )
    },

  },
};
</script>
